#include<bits/stdc++.h>
#define For(i,a,b) for(int i=a,i##end=b;i<=i##end;i++)
#define Rof(i,a,b) for(int i=a,i##end=b;i>=i##end;i--)
#define rep(i,  b) for(int i=1,i##end=b;i<=i##end;i++)
using namespace std;
const int N=1e3+9;
char buf[(1<<21)+5],*p1,*p2;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
void chmx(int &x,int y){(x<y)&&(x=y);}
void chmn(int &x,int y){(x>y)&&(x=y);}
int read(){
	int f=0,x=0;
	char ch=getchar();
	while(!isdigit(ch)){f|=(ch=='-');ch=getchar();}
	while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
	return f?-x:x;
}
int n,m,p;
int a[N][N];
int sum[N][N],iv[N][N];
vector<int>P;
int c[N][N][9];
int C[N*N][9];
void get(int x){
	for(int i=2;i*i<=x;i++)if(x%i==0){
		P.push_back(i);
		while(x%i==0)x/=i;
	}if(x!=1&&x!=p)P.push_back(x);
}
#define int long long
void exgcd(int a,int b,int &x,int &y){
	if(b==0){x=1;y=0;return;}
	exgcd(b,a%b,x,y);
	int xx=x,yy=y;
	x=yy;y=xx-a/b*yy;
}
int getinv(int x){
	int a,b;
	exgcd(x,p,a,b);
	a%=p;a+=p;a%=p;
	return a;
}
#undef int
int sta[11],top;
void write(int x){
	do sta[++top]=x%10,x/=10;while(x);
	while(top)putchar(sta[top--]+'0');putchar('\n');
}
char s[100];
signed main(){
//	printf("%.5lf\n",(&pppp-&ppp)/1024.0/1024.0);
//	int cases=read();
//	sprintf(s,"tsuki%d.in",cases);
//	freopen(s,"r",stdin);
//	sprintf(s,"tsuki%d.out",cases);
//	freopen(s,"w",stdout);
	freopen("tsuki.in","r",stdin);
	freopen("tsuki.out","w",stdout);
	n=read(),m=read(),p=read();get(p);
	For(i,0,max(n,m))sum[i][0]=sum[0][i]=iv[i][0]=iv[0][i]=1;
	rep(i,n)rep(j,m){
		a[i][j]=read();
		For(k,0,(int)P.size()-1){
			c[i][j][k]=c[i-1][j][k]+c[i][j-1][k]-c[i-1][j-1][k];
			while(a[i][j]%P[k]==0)c[i][j][k]++,a[i][j]/=P[k];
		}
		sum[i][j]=1ll*a[i][j]*sum[i-1][j]%p*sum[i][j-1]%p*iv[i-1][j-1]%p;
//		assert(__gcd(sum[i][j],p)==1);
		iv[i][j]=getinv(sum[i][j]);
//		assert(1ll*sum[i][j]*iv[i][j]%p==1);
	}
	For(i,0,(int)P.size()-1){
		C[0][i]=1;C[1][i]=P[i];
		For(j,2,n*m)C[j][i]=1ll*C[j-1][i]*P[i]%p;
	}
	int all=0;
	int q=read();rep(I,q){
		int l1=read(),r1=read(),l2=read(),r2=read();
		long long ans=1ll*sum[l2][r2]*iv[l1-1][r2]%p*iv[l2][r1-1]%p*sum[l1-1][r1-1]%p;
		For(i,0,(int)P.size()-1)
			ans=ans*C[c[l2][r2][i]-c[l1-1][r2][i]-c[l2][r1-1][i]+c[l1-1][r1-1][i]][i]%p;
		all+=(I^ans);all%=147744151;
//		cerr<<ans<<endl;
	}cout<<all<<endl;
	return 0;
}


